package allrobots.RobotThread;

import allrobots.Robot.RobotMessage;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;

public class Connected implements Runnable {
    private Integer robotId;
    private ServerSocket serverSocket;
    static ConcurrentHashMap<String, ClientHandler> clientMap = new ConcurrentHashMap<>();

    public Connected(Integer robotId, ServerSocket serverSocket) {
        this.robotId = robotId;
        this.serverSocket = serverSocket;
    }


    @Override
    public void run() {
        try {
            // 持续接收客户端连接
            while (true) {
                Socket clientSocket = serverSocket.accept(); // 接受客户端连接
                System.out.println("有物体连接机器人 " + clientSocket.getRemoteSocketAddress());
                // 为每个客户端创建一个线程来处理
                ClientHandler clientHandler = new ClientHandler(robotId,clientSocket);
                new Thread(clientHandler).start();
                // 将新客户端加入clientMap，客户端的ID可以是客户端的IP或自定义ID
                clientMap.put(clientSocket.getRemoteSocketAddress().toString(), clientHandler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
